(function ($) {
    Drupal.behaviors.aia_messages = {
        attach: function(context, settings) {

            String.prototype.format = function() {
                var args = arguments;

                return this.replace(/{(\d+)}/g, function(match, number) {
                    return typeof args[number] != 'undefined'
                        ? args[number]
                        : match
                        ;
                });
            };

            var conversation   = Drupal.settings.aia_conversation;
//            var aia_messages   = Drupal.settings.aia_messages;
            var max_message_id = Drupal.settings.max_message_id;
            var interlocutors = Drupal.settings.interlocutors;
            var template = Drupal.settings.template;

            $(document).ready(function(){
                $('#messages_scrollbar').tinyscrollbar({sizethumb: 50});
                messages_realtime_monitor();
            });

            function messages_realtime_monitor() {
                $('#messages_scrollbar').tinyscrollbar_update("bottom");
                setInterval(function() {


                    $.getJSON("/account/messages/ajax/aia_get_new_messages/" + conversation.cid + "/" + max_message_id, null, function (messages) {
                        $.each(messages, function(index, value) {
                            console.log(max_message_id);
                            if(value.mid > max_message_id) {
                                max_message_id = value.mid;

                                var hmtl = template.format(
                                    value.mid,
                                    value.ufrom,
                                    interlocutors[value.ufrom]["avatar"],
                                    interlocutors[value.ufrom]["name"],
                                    value.created,
                                    value.body
                                );

                                $("#messages-add").before(hmtl);
                                $('#messages_scrollbar').tinyscrollbar_update("bottom");
                            }

                        });
                    });
                }, 5000);
            }



            Drupal.ajax.prototype.commands.update_messages_list = function(ajax, response, status) {
                aia_get_new_messages();
            }
        }
    };

})(jQuery);